import _ from 'lodash';
import BW from './bwCommon';
import urls from './apiUrls';
import axios from 'axios';
// import qs from 'qs';

/**
 * [request Ajax 公共库]
 * @param  {[String]} apiName   [api 缩写名]
 * @param  {[Object]} paramsObj [ 参数]
 * @param  {[String]} paramsObj [ 参数]
 */
const request = function request(apiName, paramsObj, reqType) {
  paramsObj = paramsObj || {}
  if (_.isUndefined(urls[apiName])) {
    BW.Toast('接口地址未注册')
    return;
  }
  Object.assign(paramsObj, {
    openid: this.$store.getters.getOpenId ? this.$store.getters.getOpenId : ''
  })

  if (typeof (reqType) === 'undefined') reqType = 'post'

  let postParams = reqType === 'post' ? paramsObj : ''
  let getParams = reqType === 'get' ? paramsObj : ''
  console.log(postParams)
  return new Promise((resolve, reject) => {
    this.$store.commit('updateLoadingStatus', true)
    axios({
      method: reqType,
      url: urls[apiName],
      data: postParams,
      params: getParams,
      // transformRequest: [function (data) {    // 转换成表单数据格式
      //   if (reqType === 'post') data = qs.stringify(data);
      //   return data;
      // }],
      responseType: 'json',
      headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      if (!res) {
        reject({
          rspInf: '服务器 data 数据出错！'
        });
        this.$store.commit('updateLoadingStatus', false)
      }
      if (res.data) {
        if (res.data.rspCd === '00000') {
          resolve(res.data);
        } else if (res.data.rspCd === 'W0001') {
          this.$store.commit('updateLoadingStatus', false)
          this.$store.commit('updateLoginFlag', true)
          let codeUrl = encodeURIComponent(BW.funcUrlDelL(['code', 'state']))    // 移除相关参数后的url
          window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.$store.getters.getAppId + '&redirect_uri=' + codeUrl + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
        } else {
          BW.Toast(res.data.rspInf || '错误提示数据异常！')
          reject(res.data.rspInf);
          this.$store.commit('updateLoadingStatus', false)
        }
      }
    }).catch((error) => {
      this.$store.commit('updateLoadingStatus', false);
      if (error.response) {
        BW.Toast('服务器出问题了！')
        reject(error.response);
      } else {
        BW.Toast((error && error.rspInf) || '服务器出问题了！')
        reject(error);
      }
    });
  });
};

export default request;
